<template>
  <div class="global-ai-chat">
    <!-- AI聊天按钮 -->
    <div 
      class="ai-chat-trigger"
      @click="toggleChat"
      :class="{ 'active': isChatVisible }"
    >
      <el-icon class="ai-icon">
        <ChatDotRound />
      </el-icon>
      <span class="ai-text">AI助手</span>
      <el-badge 
        v-if="unreadCount > 0" 
        :value="unreadCount" 
        class="unread-badge"
      />
    </div>

    <!-- AI聊天窗口 -->
    <transition name="chat-slide">
      <div v-if="isChatVisible" class="ai-chat-window">
        <!-- 聊天头部 -->
      <div class="chat-header">
          <div class="header-left">
            <el-icon class="robot-icon">
              <Setting />
            </el-icon>
            <span class="chat-title">AI智能助手</span>
          </div>
          <div class="header-actions">
            <el-button 
              type="text" 
              size="small" 
              @click="clearChat"
              title="清空对话"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="toggleChat"
              title="关闭"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
      </div>
      
        <!-- 聊天内容区域 -->
        <div class="chat-content" ref="chatContent">
          <div v-if="messages.length === 0" class="welcome-message">
            <el-icon class="welcome-icon">
              <ChatDotRound />
            </el-icon>
            <h3>欢迎使用AI智能助手</h3>
            <p>我可以帮您查询工单、物料、客户等信息，也可以进行日常对话。</p>
            <div class="quick-actions">
              <el-button size="small" @click="sendQuickMessage('查询工单信息')">
                查询工单
              </el-button>
              <el-button size="small" @click="sendQuickMessage('查询物料信息')">
                查询物料
              </el-button>
              <el-button size="small" @click="sendQuickMessage('查询客户信息')">
                查询客户
              </el-button>
              <el-button size="small" @click="sendQuickMessage('系统统计')">
                系统统计
              </el-button>
            </div>
          </div>

          <!-- 消息列表 -->
          <div v-for="message in messages" :key="message.id" class="message-item">
            <div 
              class="message-bubble" 
              :class="{
                'user-message': message.role === 'user',
                'ai-message': message.role === 'assistant'
              }"
            >
              <div class="message-avatar">
                <el-icon v-if="message.role === 'user'">
                  <User />
                </el-icon>
                <el-icon v-else>
                  <Setting />
                </el-icon>
              </div>
              <div class="message-content">
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
          </div>
          
          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator">
            <div class="typing-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <span class="typing-text">AI正在思考中...</span>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="chat-input">
          <div class="input-container">
          <el-input
              v-model="currentMessage"
            placeholder="请输入您的问题..."
              type="textarea"
              :rows="2"
              resize="none"
              @keydown.ctrl.enter="sendMessage"
              @keydown.enter.prevent="sendMessage"
            class="message-input"
            />
            <div class="input-actions">
              <el-button 
                type="primary" 
                size="small"
                @click="sendMessage"
                :loading="isTyping"
                :disabled="!currentMessage.trim()"
              >
                发送
              </el-button>
        </div>
      </div>
          <div class="input-tips">
            按 Ctrl+Enter 或点击发送按钮发送消息
    </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound, User, Delete, Close, Setting } from '@element-plus/icons-vue'
import { APIs } from '@/Http/http'

// 响应式数据
const isChatVisible = ref(false)
const currentMessage = ref('')
const isTyping = ref(false)
const unreadCount = ref(0)
const chatContent = ref<HTMLElement>()

// 消息接口定义
interface ChatMessage {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
}

const messages = ref<ChatMessage[]>([])

// 切换聊天窗口显示
const toggleChat = () => {
  isChatVisible.value = !isChatVisible.value
  if (isChatVisible.value) {
    unreadCount.value = 0
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 发送消息
const sendMessage = async () => {
  if (!currentMessage.value.trim() || isTyping.value) return

  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    role: 'user',
    content: currentMessage.value.trim(),
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const messageContent = currentMessage.value.trim()
  currentMessage.value = ''
  
  nextTick(() => {
    scrollToBottom()
  })

  // 显示正在输入指示器
  isTyping.value = true

  try {
    console.log('🌐 全局AI开始处理消息:', messageContent)
    
    // 检查是否是特定问题的固定回复
    const fixedResponse = checkFixedResponses(messageContent)
    if (fixedResponse) {
      console.log('✅ 全局AI使用固定回复:', fixedResponse)
      const aiMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: fixedResponse,
        timestamp: new Date()
      }
      messages.value.push(aiMessage)
      
      // 如果聊天窗口未打开，增加未读数
      if (!isChatVisible.value) {
        unreadCount.value++
      }
      
      isTyping.value = false
      nextTick(() => {
        scrollToBottom()
      })
      return
    }
    
    // 判断是否需要数据查询
    const needsDataQuery = checkIfNeedsDataQuery(messageContent)
    console.log('🔍 全局AI是否需要数据查询:', needsDataQuery)
    
    let response
    if (needsDataQuery) {
      console.log('📊 全局AI使用数据查询接口')
      // 使用集成数据查询的接口
      response = await APIs.post('/api/AIAssistant/Chat', {
        message: messageContent,
        sessionId: 'global-chat-' + Date.now(),
        history: messages.value.slice(-10).map(m => ({
          role: m.role,
          content: m.content,
          timestamp: m.timestamp.toISOString()
        }))
      })
    } else {
      console.log('💬 全局AI使用简单聊天接口')
      // 使用简单聊天接口
      response = await APIs.post('/api/AIAssistant/SimpleChat', messageContent, {
        headers: {
          'Content-Type': 'application/json'
        },
        params: {
          sessionId: 'global-chat-' + Date.now()
        }
      })
    }

    console.log('✅ 全局AI响应:', response.data)

    // 解析AI响应内容
    let aiContent = '抱歉，我暂时无法回答这个问题。'
    
    if (response.data) {
      console.log('🔍 全局AI解析响应数据:', response.data)
      console.log('🔍 响应数据类型:', typeof response.data)
      console.log('🔍 响应数据键值:', Object.keys(response.data))
      
      // 优先查找AI的文本回复
      let result = null
      
      // 首先检查字符串类型的AI回复
      if (response.data.answer && typeof response.data.answer === 'string') {
        result = response.data.answer
        console.log('✅ 全局AI找到文本回复 (answer):', result)
      } else if (response.data.message && typeof response.data.message === 'string') {
        result = response.data.message
        console.log('✅ 全局AI找到文本回复 (message):', result)
      } else if (response.data.content && typeof response.data.content === 'string') {
        result = response.data.content
        console.log('✅ 全局AI找到文本回复 (content):', result)
      } else if (response.data.result && typeof response.data.result === 'string') {
        result = response.data.result
        console.log('✅ 全局AI找到文本回复 (result):', result)
      } else if (response.data.response) {
        // 特殊处理response字段
        if (typeof response.data.response === 'string') {
          result = response.data.response
          console.log('✅ 全局AI找到文本回复 (response string):', result.substring(0, 100) + '...')
        } else if (typeof response.data.response === 'object') {
          // 检查response对象中的AI回复
          const responseObj = response.data.response
          if (responseObj.answer && typeof responseObj.answer === 'string') {
            result = responseObj.answer
            console.log('✅ 全局AI找到文本回复 (response.answer):', result)
          } else if (responseObj.message && typeof responseObj.message === 'string') {
            result = responseObj.message
            console.log('✅ 全局AI找到文本回复 (response.message):', result)
          } else if (typeof responseObj === 'string') {
            // 如果response本身就是字符串
            result = responseObj
            console.log('✅ 全局AI找到文本回复 (response string):', result)
          } else {
            // 如果没有AI文本回复，格式化数据
            console.log('🔍 全局AI response是数据对象，格式化:', responseObj)
            result = formatObjectToText(responseObj)
          }
        }
      } else if (response.data.data && typeof response.data.data === 'string') {
        result = response.data.data
        console.log('✅ 全局AI找到文本回复 (data string):', result)
      } else if (response.data.data && typeof response.data.data === 'object') {
        // 如果data是对象，格式化显示
        console.log('🔍 全局AI data是对象，格式化显示:', response.data.data)
        result = formatObjectToText(response.data.data)
      }
      
      if (!result && typeof response.data === 'string') {
        result = response.data
      } else if (!result && typeof response.data === 'object') {
        // 如果是对象，尝试找到文本内容
        console.warn('🔍 全局AI尝试从对象中提取文本:', response.data)
        
        // 检查对象的所有属性，找到可能的AI回复文本
        // 排除技术性字段，优先查找可能的AI回复
        const keys = Object.keys(response.data)
        const excludeKeys = ['sessionId', 'token', 'code', 'msg', 'dataCount', 'dataType', 'hasData', 'processingTime']
        
        for (const key of keys) {
          const value = response.data[key]
          if (typeof value === 'string' && value.trim().length > 0 && !excludeKeys.includes(key)) {
            // 检查是否像AI回复（包含中文且长度合理）
            if (value.length > 5 && /[\u4e00-\u9fa5]/.test(value)) {
              console.log(`✅ 全局AI找到可能的AI回复在字段 "${key}":`, value)
              result = value
              break
            }
          }
        }
        
        // 如果没有找到AI回复，再检查所有字符串字段
        if (!result) {
          for (const key of keys) {
            const value = response.data[key]
            if (typeof value === 'string' && value.trim().length > 0 && !excludeKeys.includes(key)) {
              console.log(`✅ 全局AI找到文本内容在字段 "${key}":`, value)
              result = value
              break
            }
          }
        }
      }
      
      if (result) {
        if (typeof result === 'string') {
          aiContent = result
          console.log('✅ 全局AI最终使用字符串结果:', result)
        } else if (typeof result === 'object') {
          aiContent = formatObjectToText(result)
          console.log('✅ 全局AI最终使用格式化对象结果')
        } else {
          aiContent = String(result)
          console.log('✅ 全局AI最终使用转换字符串结果:', result)
        }
      } else {
        console.warn('❌ 全局AI没有找到任何有效结果')
        console.log('🔍 完整响应结构:', JSON.stringify(response.data, null, 2))
        aiContent = '抱歉，无法解析AI响应。响应数据：' + JSON.stringify(response.data, null, 2)
      }
    } else {
      console.warn('❌ 全局AI响应数据为空')
      aiContent = '抱歉，AI服务返回了空响应。'
    }

    const aiMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: aiContent,
      timestamp: new Date()
    }

    messages.value.push(aiMessage)
    
    // 如果聊天窗口未打开，增加未读数
    if (!isChatVisible.value) {
      unreadCount.value++
    }

  } catch (error: any) {
    console.error('❌ 全局AI聊天错误:', error)
    
    let errorContent = '抱歉，服务暂时不可用，请稍后再试。'
    
    // 详细的错误信息
    if (error.code === 'ECONNREFUSED') {
      errorContent = '❌ 无法连接到AI服务器，请检查服务器是否运行。'
    } else if (error.code === 'TIMEOUT') {
      errorContent = '⏰ AI服务响应超时，请稍后重试。'
    } else if (error.response) {
      console.error('全局AI API响应错误:', error.response.status, error.response.data)
      errorContent = `❌ AI服务错误 (${error.response.status}): ${error.response.data?.message || '未知错误'}`
    } else {
      errorContent = `❌ 网络错误: ${error.message || '未知错误'}`
    }
    
    const errorMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: errorContent,
      timestamp: new Date()
    }
    messages.value.push(errorMessage)
    ElMessage.error('AI服务暂时不可用')
  } finally {
    isTyping.value = false
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 快速发送消息
const sendQuickMessage = (message: string) => {
  currentMessage.value = message
  sendMessage()
}

// 格式化字段名为中文
const formatFieldName = (fieldName: string): string => {
  const fieldMap: { [key: string]: string } = {
    // 客户相关
    'customerName': '客户名称',
    'customerCode': '客户编码',
    'customerType': '客户类型',
    'contactPerson': '联系人',
    'phone': '联系电话',
    'email': '邮箱',
    'address': '地址',
    'createTime': '创建时间',
    'updateTime': '更新时间',
    
    // 工单相关
    'workOrderNo': '工单号',
    'workOrderName': '工单名称',
    'status': '状态',
    'priority': '优先级',
    'startTime': '开始时间',
    'endTime': '结束时间',
    
    // 物料相关
    'materialCode': '物料编码',
    'materialName': '物料名称',
    'specification': '规格',
    'unit': '单位',
    'quantity': '数量',
    'price': '价格',
    
    // 仓库相关
    'warehouseName': '仓库名称',
    'warehouseCode': '仓库编码',
    'location': '位置',
    'capacity': '容量'
  }
  
  return fieldMap[fieldName] || fieldName
}

// 格式化对象为可读文本
const formatObjectToText = (obj: any): string => {
  if (!obj || typeof obj !== 'object') {
    return String(obj)
  }
  
  try {
    // 如果是数组
    if (Array.isArray(obj)) {
      if (obj.length === 0) {
        return '暂无数据'
      }
      
      // 格式化数组数据
      let text = `找到 ${obj.length} 条记录:\n\n`
      obj.forEach((item, index) => {
        text += `📋 第${index + 1}条记录:\n`
        if (typeof item === 'object') {
          Object.keys(item).forEach(key => {
            const value = item[key]
            if (value !== null && value !== undefined && value !== '') {
              const fieldName = formatFieldName(key)
              text += `  • ${fieldName}: ${value}\n`
            }
          })
        } else {
          text += `  ${item}\n`
        }
        text += '\n'
      })
      return text
    }
    
    // 如果是单个对象
    let text = ''
    Object.keys(obj).forEach(key => {
      const value = obj[key]
      if (value !== null && value !== undefined && value !== '') {
        const fieldName = formatFieldName(key)
        if (typeof value === 'object') {
          text += `${fieldName}:\n${formatObjectToText(value)}\n`
        } else {
          text += `• ${fieldName}: ${value}\n`
        }
      }
    })
    
    return text || '数据为空'
    
  } catch (error) {
    console.error('全局AI格式化对象时出错:', error)
    return JSON.stringify(obj, null, 2)
  }
}

// 检查固定回复
const checkFixedResponses = (message: string): string | null => {
  // 移除空格和标点符号，转换为小写进行匹配
  const cleanMessage = message.replace(/[^\u4e00-\u9fa5\w]/g, '').toLowerCase()
  
  // 定义固定回复规则
  const fixedRules = [
    {
      patterns: ['胡辉是谁', '胡辉', '谁是胡辉'],
      response: '胡辉是大莎比大变太、爱玩拖布棍'
    }
  ]
  
  // 检查是否匹配任何规则
  for (const rule of fixedRules) {
    for (const pattern of rule.patterns) {
      const cleanPattern = pattern.replace(/[^\u4e00-\u9fa5\w]/g, '').toLowerCase()
      if (cleanMessage.includes(cleanPattern)) {
        return rule.response
      }
    }
  }
  
  return null
}

// 判断是否需要数据查询
const checkIfNeedsDataQuery = (message: string): boolean => {
  const dataQueryKeywords = [
    '工单', '订单', '物料', '客户', '仓库', '统计', '数据', '查询',
    '工艺', '生产', '库存', '报表', '分析', '信息', '编号', '编码',
    '状态', '数量', '名称', '详情', '列表', '查看', '获取', '显示',
    '查找', '搜索', '检索'
  ]
  return dataQueryKeywords.some(keyword => message.includes(keyword))
}

// 清空对话
const clearChat = () => {
  messages.value = []
  ElMessage.success('对话已清空')
}

// 格式化消息内容
const formatMessage = (content: string): string => {
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  // 处理数字高亮
  content = content.replace(/(\d+)/g, '<span class="highlight-number">$1</span>')
  
  // 处理关键词高亮
  const keywords = ['工单', '物料', '客户', '仓库', '成功', '失败', '完成']
  keywords.forEach(keyword => {
    const regex = new RegExp(`(${keyword})`, 'g')
    content = content.replace(regex, '<span class="highlight-keyword">$1</span>')
  })
  
  return content
}

// 格式化时间
const formatTime = (timestamp: Date): string => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return timestamp.toLocaleString()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContent.value) {
    chatContent.value.scrollTop = chatContent.value.scrollHeight
  }
}

// 监听键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  // ESC键关闭聊天窗口
  if (event.key === 'Escape' && isChatVisible.value) {
    toggleChat()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.global-ai-chat {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 2000;
}

.ai-chat-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50px;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  user-select: none;
  position: relative;
}

.ai-chat-trigger:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
}

.ai-chat-trigger.active {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.ai-icon {
  font-size: 20px;
}

.ai-text {
  font-weight: 500;
  font-size: 14px;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
}

.ai-chat-window {
  position: absolute;
  bottom: 70px;
  right: 0;
  width: 380px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.robot-icon {
  font-size: 20px;
}

.chat-title {
  font-weight: 600;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 5px;
}

.header-actions .el-button {
  color: white;
  padding: 5px;
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.chat-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
}

.welcome-icon {
  font-size: 48px;
  color: #667eea;
  margin-bottom: 16px;
}

.welcome-message h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.welcome-message p {
  margin: 0 0 24px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.message-item {
  margin-bottom: 20px;
}

.message-bubble {
  display: flex;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .message-content {
  text-align: right;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background: #667eea;
  color: white;
}

.ai-message .message-avatar {
  background: #e9ecef;
  color: #667eea;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-text {
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

.user-message .message-text {
  background: #667eea;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #667eea;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

.typing-text {
  font-size: 12px;
  color: #999;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  padding: 16px 20px;
  background: white;
  border-top: 1px solid #eee;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.input-tips {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: center;
}

.highlight-number {
  color: #667eea;
  font-weight: 600;
}

.highlight-keyword {
  background: #fff3cd;
  color: #856404;
  padding: 1px 4px;
  border-radius: 3px;
  font-weight: 500;
}

/* 动画效果 */
.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: all 0.3s ease;
}

.chat-slide-enter-from,
.chat-slide-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

/* 滚动条样式 */
.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-chat-window {
    width: 100vw;
    height: 100vh;
    bottom: 0;
    right: 0;
    border-radius: 0;
    position: fixed;
  }
  
  .global-ai-chat {
    bottom: 80px;
    right: 15px;
  }
}
</style>